package com.yan.token.service;

import com.yan.token.storage.CredentialStorage;
import com.yan.token.storage.H2CredentialStorage;

/**
 * @author yanheng
 * @data 2019/12/11 10:37
 */
public class DefaultApiAuthencathor implements  ApiAuthencathor {

    private CredentialStorage credentialStorage;

    public DefaultApiAuthencathor(){
        this.credentialStorage = new H2CredentialStorage();
    }

    public DefaultApiAuthencathor(CredentialStorage credentialStorage){
        this.credentialStorage = credentialStorage;
    }
    @Override
    public void auth(String url) {
        ApiRequest apiRequest = ApiRequest.createFromFullUrl(url);
        auth(apiRequest);
    }

    @Override
    public void auth(ApiRequest apiRequest){
        String appId = apiRequest.getAppId();
        String token = apiRequest.getToken();
        String originalUrl = apiRequest.getOriginalUrl();
        long timestamp = apiRequest.getTimestamp();

        AuthToken clientAuthToken = new AuthToken(token, timestamp);
        if (clientAuthToken.isExpired()){
            throw new RuntimeException("Token is expired");
        }

        String password = credentialStorage.getPasswordByAppId(appId);
        AuthToken serverAuthToken = AuthToken.generate(originalUrl, appId, password, timestamp);
        if (!serverAuthToken.match(clientAuthToken)){
            throw new RuntimeException("Token verfication failed");
        }
    }
}
